<template>
  <div>
    <HeaderNav />
    <div class="operate-dict">
      <div class="filter-view">
        <!-- 日期时间筛选 -->
        <span>日期时间：</span>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px;"
          value-format="YYYY-MM-DD"
        />

        <!-- 关键词搜索 -->
        <span>筛选器：</span>
        <el-input
          v-model="filterSearch"
          style="width: 240px; margin-right: 20px;"
          placeholder="搜索（用户/IP/操作内容）"
          :suffix-icon="Search"
        />

        <!-- 搜索按钮 -->
        <button class="btn-base search-btn" @click="handleSearch">搜索</button>
        <el-button @click="refreshLogs" :loading="loading" style="margin-left: 10px;">刷新</el-button>
      </div>
      <div class="data-table" style="margin-top: 20px;">
        <MainTable
          :loading="loading"
          :logs-data="logsData"
          :pagination="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @view-detail="viewLogDetail"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import HeaderNav from '@/components/HeaderNav.vue'
import MainTable from './components/MainTable.vue'
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Search } from '@element-plus/icons-vue'
import { getOperationLogs } from '@/api/logs'

// 1. 路由
const router = useRouter();

// 2. 关键词搜索
const filterSearch = ref('')

// 3. 日期范围选择
const dateRange = ref([])

// 4. 操作日志数据
const logsData = ref([])

// 5. 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  totalPages: 0
})

// 6. 加载状态
const loading = ref(false)

// 7. 搜索按钮点击事件
const handleSearch = () => {
  // 重置到第一页
  pagination.value.currentPage = 1
  fetchOperationLogs()
};

// 8. 获取操作日志数据
const fetchOperationLogs = async () => {
  loading.value = true
  try {
    // 构造查询参数
    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }

    // 添加日期范围参数
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }

    // 添加搜索关键词参数
    if (filterSearch.value) {
      params.userName = filterSearch.value
    }

    const response = await getOperationLogs(params)

    if (response.code === 200) {
      logsData.value = response.data.list.map(log => ({
        id: log.id,
        name: log.user_name,
        operationModule: log.method,
        operationContent: log.url,
        ipAddress: log.ip_address,
        operationTime: log.created_at,
        operationStatus: log.status_code === 200 ? '操作成功' : '操作失败',
        statusCode: log.status_code,
        duration: log.duration
      }))

      pagination.value.total = response.data.pagination.total
      pagination.value.totalPages = response.data.pagination.totalPages
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
  } finally {
    loading.value = false
  }
}

// 9. 刷新日志
const refreshLogs = () => {
  fetchOperationLogs()
}

// 10. 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  fetchOperationLogs()
}

// 11. 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchOperationLogs()
}

// 12. 查看日志详情
const viewLogDetail = (row) => {
  // 跳转到详情页
  router.push(`/operatedict/detail/${row.id}`);
}

// 13. 组件挂载时获取数据
onMounted(() => {
  fetchOperationLogs()
});
</script>

<style scoped lang="scss">
.operate-dict {
  padding: 20px;
  height: 100vh;
  background-color: rgb(242, 247, 251);

  .filter-view {
    background-color: rgb(250, 252, 249);
    padding: 16px;
    display: flex;
    align-items: center;
    border-radius: 4px;

    span {
      color: #666;
      font-size: 14px;
      margin-right: 10px;
    }
  }

  .data-table {
    background-color: rgb(250, 252, 249);
    padding: 16px;
    border-radius: 4px;
  }
}
</style>
